/**
 * OSS is a Open Service Container which gives the leverage of building the Desktop and Web
 * Application. * Copyright (C) 2008-2009  Ponraj Sutanthiramani
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Or5e Open Source Community
 * Navigator Bldg, ITPL, Bangalore, India.
 */
package org.or5e.api.calendar;

import java.io.IOException;
import java.util.Calendar;
import java.util.StringTokenizer;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.or5e.core.BaseUtils;

/**
 * @author Ponraj Suthanthiramani
 */
public class LoadXLFile extends DataFileLoader {
    private Workbook workbook = null;
    private Sheet sheet = null;
    private int currentLine;
    private int maxColumns;
    private int maxRow;
    private String[] colName = null;
    private BaseUtils utils = BaseUtils.getUtility();
    @Override
    public synchronized CalendarEntry getNextEntry() {
        CalendarEntry entry = new CalendarEntry();

        if(currentLine > maxRow) {
            return null;
        }
        
        Cell subjectCell = sheet.getCell(0, currentLine);
        if(subjectCell != null && utils.isEmptyString(subjectCell.getContents())) {
            return null;
        }

        Cell startDateCell = sheet.getCell(1, currentLine);
        Cell startTimeCell = sheet.getCell(2, currentLine);
        Cell endDateCell = sheet.getCell(3, currentLine);
        Cell endTimeCell = sheet.getCell(4, currentLine);
        Cell alldayeventCell = sheet.getCell(5, currentLine);
        Cell reminderonoffCell =  sheet.getCell(6, currentLine);
        Cell reminderDateCell =  sheet.getCell(7, currentLine);
        Cell reminderTimeCell =  sheet.getCell(8, currentLine);
        Cell meetingOrganizerCell =  sheet.getCell(9, currentLine);
        Cell requiredAttendeesCell =  sheet.getCell(10, currentLine);
        Cell optionalAttendeesCell =  sheet.getCell(11, currentLine);
        Cell meetingResourcesCell =  sheet.getCell(12, currentLine);
        Cell billingInformationCell =  sheet.getCell(13, currentLine);
        Cell categoriesCell =  sheet.getCell(14, currentLine);
        Cell descriptionCell =  sheet.getCell(15, currentLine);
        Cell locationCell =  sheet.getCell(16, currentLine);
        Cell mileageCell =  sheet.getCell(17, currentLine);
        Cell priorityCell =  sheet.getCell(18, currentLine);
        Cell privateCell =  sheet.getCell(19, currentLine);
        Cell sensitivityCell =  sheet.getCell(20, currentLine);
        Cell showtimeasCell =  sheet.getCell(21, currentLine);

        entry.setAlldayevent(Boolean.getBoolean(alldayeventCell.getContents()));
        entry.setBillingInformation(billingInformationCell.getContents());
        entry.setCategories(categoriesCell.getContents());
        entry.setDescription(descriptionCell.getContents());
        entry.setEndDateTime(getCalendar(endDateCell.getContents(), endTimeCell.getContents()));
        entry.setLocation(locationCell.getContents());
        entry.setMeetingOrganizer(meetingOrganizerCell.getContents());
        entry.setMeetingResources(meetingResourcesCell.getContents());
        entry.setMileage(mileageCell.getContents());
        entry.setOptionalAttendees(getStringArray(optionalAttendeesCell.getContents()));
        entry.setPriority(CalendarEntry.Priority.HIGH);
        entry.setPrivate(Boolean.getBoolean(privateCell.getContents()));
        entry.setPrivate(Boolean.getBoolean(priorityCell.getContents()));
        entry.setReminderDateTime(getCalendar(reminderDateCell.getContents(), reminderTimeCell.getContents()));
        entry.setReminderonoff(Boolean.getBoolean(reminderonoffCell.getContents()));
        entry.setRequiredAttendees(getStringArray(requiredAttendeesCell.getContents()));
        entry.setSensitivity(sensitivityCell.getContents());
        entry.setShowTimeAs(Integer.parseInt(showtimeasCell.getContents()));
        entry.setStartDateTime(getCalendar(startDateCell.getContents(), startTimeCell.getContents()));
        entry.setSubject(subjectCell.getContents());
        currentLine++;
        return entry;
    }

    @Override
    public String getName() {
        return "LoadXLFile";
    }
    private String[] getStringArray(String content) {
        StringTokenizer orgTolen = new StringTokenizer(content, ";");
        int totalCnt = orgTolen.countTokens();
        String[] optionalAtt = new String[totalCnt];
        for(int index = 0 ; index < totalCnt ; index ++) {
            optionalAtt[index] = orgTolen.nextToken();
        }
        return optionalAtt;
    }
    private Calendar getCalendar(String date, String time) {
        Calendar cal = Calendar.getInstance();

        StringTokenizer dtToken = new StringTokenizer(date, "/");
        cal.set(Calendar.MONTH, Integer.parseInt(dtToken.nextToken())-1);
        cal.set(Calendar.DATE, Integer.parseInt(dtToken.nextToken())-1);
        cal.set(Calendar.YEAR, Integer.parseInt(dtToken.nextToken()));

        StringTokenizer timeToken = new StringTokenizer(time, ":");
        cal.set(Calendar.HOUR, Integer.parseInt(timeToken.nextToken()));
        cal.set(Calendar.MINUTE, Integer.parseInt(timeToken.nextToken()));
        cal.set(Calendar.SECOND, Integer.parseInt(timeToken.nextToken().substring(0, 1)));

        return cal;
    }

    @Override
    public synchronized boolean initilize() {
        try {
            if(workbook != null) {
                workbook.close();
            }
            workbook = Workbook.getWorkbook(this.getLoadFile());
            sheet = workbook.getSheet(0);
            currentLine = 0;
            maxColumns = sheet.getColumns();
            maxRow = sheet.getRows();
            colName = new String[maxColumns];
            for (int index = 0; index < maxColumns ; index ++) {
                colName[index] = sheet.getCell(index, currentLine).getContents();
            }
            currentLine++;
        }
        catch (IOException ex) {
            return false;
        }
        catch (BiffException ex) {
            return false;
        }
        return true;
    }
}